package com.zhengqiangblog.blog.service;

import java.util.List;

import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.cache.ArticleCache;
import com.zhengqiangblog.blog.cache.CategoryCache;
import com.zhengqiangblog.blog.model.Category;
import com.zhengqiangblog.core.ApplicationContext;

public class CategoryService {

	private static final Logger logger = Logger.getLogger(CategoryService.class);

	private CategoryCache categoryCache = ApplicationContext.get(CategoryCache.class);
	private ArticleCache articleCache = ApplicationContext.get(ArticleCache.class);

	public CategoryService() {
		logger.info("CategoryService initializing...");
	}

	public int saveCategory(Category category) throws Exception {
		return categoryCache.saveCategory(category);
	}

	public int deleteCategory(int categoryId) throws Exception {
		return categoryCache.deleteCategory(categoryId);
	}

	public List<Category> getCategoryList() throws Exception {
		List<Category> categoryList = categoryCache.getCategoryList();
		for (int i = 0; i < categoryList.size(); i++) {
			Category category = categoryList.get(i);
			int articles = articleCache.getArticleCountByCategory(category.getId());
			category.setArticles(articles);
		}
		return categoryList;
	}

	public Category getCategory(int categoryId) throws Exception {
		return categoryCache.getCategory(categoryId);
	}

	public int updateCategory(Category category) throws Exception {
		return categoryCache.updateCategory(category);
	}

}
